package fsmi.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import fsmi.daoservice.StudentDAO;

public class StudentDB implements StudentDAO {

	private DBPool pool;
	private Connection conn;
	private PreparedStatement stmt;

	public StudentDB() {
		pool = DBPool.getInstance();
		if (pool.getConnCount() != 0) {
			conn = pool.getConn();
		}
	}

	@Override
	public boolean checkStuExsits(String stuID) {
		// TODO Auto-generated method stub
		boolean userExists = false;
		String sql = "select * from Student where sid=?;";
		try {
			stmt = conn.prepareStatement(sql);
			stmt.setString(1, stuID);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		ResultSet result = null;
		try {
			result = stmt.executeQuery();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
			if (result.next()) {
				userExists = true;
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return userExists;
	}

	@Override
	public boolean checkStuPassword(String stuID, String password) {
		// TODO Auto-generated method stub
		boolean passwordOk = false;
		String sql = "select * from Student where sid=? and password=?;";
		try {
			stmt = conn.prepareStatement(sql);
			stmt.setString(1, stuID);
			stmt.setString(2, password);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		ResultSet result = null;
		try {
			result = stmt.executeQuery();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
			if (result.next()) {
				passwordOk = true;
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return passwordOk;
	}

	public void destroyStudentDB() {
		try {
			stmt.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		stmt = null;
		pool.returnConn(conn);
		conn = null;
		pool = null;
	}

}
